package com.sinsz.common.interceptor;

import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 访问请求日志拦截器
 * @author chenjianbo
 * @date 2018-12-3
 */
public class LogsInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(LogsInterceptor.class);

    private static final String CURRENT_TIME = "_log_info_interceptor";

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {
        Long currentTime = System.currentTimeMillis();
        request.setAttribute(CURRENT_TIME, currentTime);
        return true;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler, Exception ex) {
        String remoteHost = request.getRemoteHost();
        String requestUri = request.getRequestURI();
        String method = request.getMethod();
        Long currentTime = (Long) request.getAttribute(CURRENT_TIME);
        currentTime = currentTime == null ? -1L : System.currentTimeMillis() - currentTime;
        String params = requestParams(request);
        String bodyParams = requestBodyParams(request);
        logger.info("请求地址:{}, 路径:{}, 请求方式:{}, 请求耗时:{}毫秒, \n请求参数：[[[ {} ]]] ~ [[[ {} ]]]",remoteHost, requestUri,method, currentTime, params, bodyParams);
    }

    private static String requestBodyParams(HttpServletRequest request) {
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream is = request.getInputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return new String(baos.toByteArray(),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    private static String requestParams(HttpServletRequest request) {
        return Json.toJson(request.getParameterMap(), JsonFormat.tidy());
    }

}
